#include "opencv2/opencv.hpp"

#include <stdio.h>

using namespace cv;
using namespace std;

int edgeThresh = 1;
Mat image, gray, equalized, edge, final;

//// define a trackbar callback
//void onTrackbar(int, void*)
//{
//	blur(gray, edge, Size(3,3));
//
//	// Run the edge detector on grayscale
//	Canny(edge, edge, edgeThresh, edgeThresh*3, 3);
//	cedge = Scalar::all(0);
//
//	image.copyTo(cedge, edge);
//	imshow("Edge map", cedge);
//}

void help()
{
	printf("\nThis sample demonstrates Canny edge detection\n"
		"Call:\n"
		"	/.edge [image_name -- Default is fruits.jpg]\n\n");
}

const char* keys = 
{
	"{1| |fruits.jpg|input image name}"
};

int main( int argc, const char** argv )
{
	help();

	CommandLineParser parser(argc, argv, keys);
	string filename = parser.get<string>("1");

	image = imread(filename, 1);
	if(image.empty())
	{
		printf("Cannot read image file: %s\n", filename.c_str());
		help();
		return -1;
	}
	final.create(image.size(), image.type());
	cvtColor(image, gray, CV_BGR2GRAY);

	// Create a window
	namedWindow("Edge map", 1);

	/// Apply Histogram Equalization

	imshow("Edge map", gray);
	waitKey(0);

	blur(gray, gray, Size(3,3));

	equalizeHist(gray, equalized);
	imshow("Edge map", equalized);
	waitKey(0);

	Canny( equalized, edge, 50, 200, 3 );
	imshow("Edge map", edge);
	waitKey(0);

	vector<Vec4i> lines;
	HoughLinesP(edge, lines, 1, CV_PI/180, 50, 50, 10 );
	for( size_t i = 0; i < lines.size(); i++ )
	{
		Vec4i l = lines[i];
		line( final, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);
	}

	imshow("Edge map", final);
	// create a toolbar
	//createTrackbar("Canny threshold", "Edge map", &edgeThresh, 100, onTrackbar);

	// Show the image
	//onTrackbar(0, 0);

	// Wait for a key stroke; the same function arranges events processing
	waitKey(0);

	return 0;
}
